<?php

namespace app\common\traits;

use ip138\Ip138;
use ShidianUtil\Utils\ConvertUtil;
use ShidianUtil\Utils\TimeUtil;
use think\db\Query;
use function app;
use function is_blank;

/**
 * 基于时间的缓存
 * Trait TimeCacheTrait
 * @package app\common\traits
 * @method timeRangeCache(?int $s_time, ?int $e_time, string $s_field = 's_time', string $e_field = 'e_time', $time = null)
 */
trait TimeCacheTrait
{

    /**
     * 如果查询时间范围在指定时间前，那么缓存查询结果
     * @param Query $query
     * @param $time
     * @return void
     */
    public function scopeTimeRangeCache(Query $query, ?int $s_time, ?int $e_time, string $s_field = 's_time', string $e_field = 'e_time', $time = null){
        if(is_null($time)){
            $time = time();
        }
        $time = TimeUtil::stamp(TimeUtil::DAY, $time);

        if (!is_null($s_time)) {
            $query->where($e_field, '>=', $s_time);
        }

        if (!is_null($e_time)) {
            $query->where($s_field, '<=', $e_time);
        }

        if($e_time < $time){
            $query->cache(true, 30 * 86400);
        }

    }
}